package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;

import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.dto.AlertRuleDto;

import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;

import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author sjqn
 */
@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Value("${zzyl.alert.deviceMaintainerRole}")
    String deviceMaintainerRole;
    @Value("${zzyl.alert.managerRole}")
    String managerRole;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private AlertDataMapper alertDataMapper;


    /**
     * 新增报警规则
     *
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     * 调用一下更新的方法 来计算
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }

    /**
     * 报警信息数据处理器
     *
     * @param deviceDataVo
     */
    @Override
    public void alertFilter(DeviceDataVo deviceDataVo) {
        // 获取数据上报的时间
        LocalDateTime alarmTime = deviceDataVo.getAlarmTime();
        // 判断一下 过滤一下时间过期的数据
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }
        // 获取该属性的所有的规则
        List<AlertRule> allAlertRuleList = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), "-1", deviceDataVo.getProductKey());
        // 获取该设备上的所有的规则
        List<AlertRule> theAlertRuleList = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), deviceDataVo.getIotId(), deviceDataVo.getProductKey());
        // 将这两个报警规则的集合进行合并
        Collection<AlertRule> alertRules = CollUtil.addAll(allAlertRuleList, theAlertRuleList);
        if (CollectionUtil.isEmpty(alertRules)) {
            return;
        }
        // 遍历每一条的规则
        alertRules.forEach(alertRule -> {
            deviceDateAlarmHandler(deviceDataVo, alertRule);
        });

    }

    /**
     * 设备数据报警处理器
     *
     * @param deviceDataVo
     * @param alertRule
     */
    private void deviceDateAlarmHandler(DeviceDataVo deviceDataVo, AlertRule alertRule) {
        // 第一次进行校验 上报数据是否在 有效检查的时间内
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        // 获取上报的时间
        LocalTime time = LocalDateTimeUtil.of(deviceDataVo.getAlarmTime()).toLocalTime();
        // 判断一下 是否在有效的时间内
        if (startTime.isAfter(time) || endTime.isBefore(time)) {
            return;
        }
        // 第二次进行校验 校验数据是否超过阈值
        String iotId = deviceDataVo.getIotId();
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
        // 跟阈值进行比较
        int result = NumberUtil.compare(Double.valueOf(deviceDataVo.getDataValue()), alertRule.getValue());
        // 判断 还有那个不等式
        if ((ObjectUtil.equal(alertRule.getOperator(), ">=") && result >= 0) || ObjectUtil.equal(alertRule.getOperator(), "<") && result < 0) {
            log.debug("该设备数据值达到了阈值");
        } else {
            // 删除记录的次数
            redisTemplate.delete(aggCountKey);
            return;
        }
        // 第三次校验 校验设备的报警数据是否处于沉默周期
        String slientCacheKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
        // 判断一下是否为空
        String slientValue = redisTemplate.opsForValue().get(slientCacheKey);
        if (StringUtils.isNotEmpty(slientValue)) {
            return;
        }
        // 第四次校验 就是校验持续周期的次数 是否相等
        String aggCount = redisTemplate.opsForValue().get(aggCountKey);
        Integer  aggDeviceDataCount = ObjectUtil.isEmpty(aggCount) ? 1 : Integer.parseInt(aggCount) + 1;
        // 判断一下
        if(ObjectUtil.notEqual(aggDeviceDataCount,alertRule.getDuration())){
            // 需要将redis里面的数据更新一下
            redisTemplate.opsForValue().set(aggCountKey,aggDeviceDataCount+"");
            return;
        }
        // 校验都通过了
        // 现在就要存储报警的数据了
        redisTemplate.delete(aggCountKey);
        // 设置沉默的周期
        redisTemplate.opsForValue().set(slientCacheKey,deviceDataVo.getDataValue(),alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        // 获取通知的用户ID
        List<Long> consumerIds = null;
        if(ObjectUtil.equal(0,alertRule.getAlertDataType())){
            // 老人异常的数据
            if(deviceDataVo.getLocationType()==0){
                // 随身设备
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            } else if (deviceDataVo.getLocationType()==1 && deviceDataVo.getPhysicalLocationType()==2) {

                consumerIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }

        }else {
            // 设备异常的数据
           consumerIds = userRoleMapper.selectByRoleName(deviceMaintainerRole);
        }
        // 查询超级管理员的ID集合
        List<Long> managerIds = userRoleMapper.selectByRoleName(managerRole);
        List<Long> allConsumerIds = CollUtil.addAllIfNotContains(consumerIds, managerIds);

        // 新增报警数据 到数据库里面的数据表中
        List<AlertData>  alertDataList = insertAlertData(deviceDataVo, alertRule, allConsumerIds);
        // 拿到要通知的用户ID信息
        List<Long> userIds = alertDataList.stream().map(AlertData::getUserId).collect(Collectors.toList());
        // 定义一个通知的方法
        webSocketNotify(alertRule,alertDataList.get(0),allConsumerIds);
    }
     @Autowired
     private WebSocketServer webSocketServer;
    /**
     * 服务端给客户端发送报警的信息数据
     * @param alertRule
     * @param alertData
     * @param userIds
     */
    private void webSocketNotify(AlertRule alertRule, AlertData alertData, List<Long> userIds) {
        AlertNotifyDto  alterNotifyDto = BeanUtil.toBean(alertData, AlertNotifyDto.class);
        alterNotifyDto.setFunctionName(alertRule.getFunctionName());
        alterNotifyDto.setAlertDataType(alertData.getType());
        alterNotifyDto.setNotifyType(1);
        // 给指定的用户的发送报警的数据信息
        webSocketServer.sendMessageToConsumer(alterNotifyDto,userIds);

    }

    /**
     * 定义插入报警数据信息的方法
     * @param deviceDataVo
     * @param alertRule
     * @param allConsumerIds
     *
     */
    private List<AlertData> insertAlertData(DeviceDataVo deviceDataVo, AlertRule alertRule, List<Long> allConsumerIds) {
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setStatus(0);

        // 遍历集合 设置userId 的值
        List<AlertData> list = allConsumerIds.stream().map(id -> {
            AlertData data = BeanUtil.toBean(alertData, AlertData.class);
            data.setUserId(id);
            return data;
        }).collect(Collectors.toList());
        // 批量插入报警的数据
        alertDataMapper.batchInsert(list);
        return list;

    }

}
